using Avalonia;
using Avalonia.Controls;
using System.Threading.Tasks;
using System;

namespace alwitTest
{
    public partial class SerialPortTest : Window
    {
        private bool _done;

        private ListBox? m_serialPortInfo = null;

        public SerialPortTest()
        {
            this.CanResize = false;
            InitializeComponent();
            var iv = this.GetObservable(Window.IsVisibleProperty);
            iv.Subscribe(async value =>
            {
                await Task.Delay(1);
                if (value && !_done)
                {
                    _done = true;
                    SetWindowStartupLocationWorkaround();
                }
            });

            InitHMI();
            Init();

        }

        private void SetWindowStartupLocationWorkaround()
        {
            if (OperatingSystem.IsWindows())
            {
                // Not needed for Windows
                return;
            }

            var scale = PlatformImpl?.DesktopScaling ?? 1.0;
            var powner = Owner?.PlatformImpl;
            if (powner != null)
            {
                scale = powner.DesktopScaling;
            }

            var rect = new PixelRect(PixelPoint.Origin, PixelSize.FromSize(ClientSize, scale));

            if (WindowStartupLocation == WindowStartupLocation.CenterScreen)
            {
                var screen = Screens.ScreenFromPoint(powner?.Position ?? Position);
                if (screen == null)
                {
                    return;
                }

                Position = screen.WorkingArea.CenterRect(rect).Position;
            }
            else
            {
                if (powner == null || WindowStartupLocation != WindowStartupLocation.CenterOwner)
                {
                    return;
                }

                Position = new PixelRect(powner.Position, PixelSize.FromSize(powner.ClientSize, scale)).CenterRect(rect)
                    .Position;
            }
        }

        private void Init()
        {
            this.m_serialPortInfo = this.FindControl<ListBox>("lbSerialPortInfo");
            this.m_serialPortInfo.Items = null;
        }

        private void InitHMI()
        {
            this.Width = 800;
            this.Height = 550;
        }

        internal class SerialInfoItem
        {
            public string ReceiveDetailText { get; set; }
        }

    }
}
